package com.zhou.util;

import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.json.XML;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created by zhouyongjun on 2020/9/2
 * 使用org.json将XML文件转换成JSON
 * 优点：
 *  自动转成：boolean 和 整行
 *  {"vfs":{"vfs_switch":true,"file":[{"name":"vfs.xml"},{"name":"config.properties"}],"interval_second":10}}
 */
public class XmlToJSONUtil {
    public static String xml2JsonString(String classPathFileName) throws Exception {
        InputStream in = XmlToJSONUtil.class.getClassLoader().getResourceAsStream(classPathFileName);
        String xml = IOUtils.toString(in);
        JSONObject xmlJSONObj = XML.toJSONObject(xml);
        return xmlJSONObj.toString();
    }
    public static String xml2JsonString(InputStream in) throws Exception {
        String xml = IOUtils.toString(in);
        JSONObject xmlJSONObj = XML.toJSONObject(xml);

        return xmlJSONObj.toString();
    }
    public static String xml2JsonString(File file) throws Exception {
      return xml2JsonString(new FileInputStream(file));
    }



    public static void main(String[] args) throws Exception {

        String string = xml2JsonString("vfs.xml");
        System.out.println(string);
        System.out.println(XmlDom4jUtils.xml2JSON("vfs.xml"));
//        System.out.println(XmlDom4jUtils.jsonToPrettyXml(XmlDom4jUtils.xml2JSON("vfs.xml")));

    }
}
